import React, { Component, CSSProperties } from 'react';

import {
    fetchMyMusics,
    fetchMySimpleInfo,
    fetchViewHistory
} from '../../core/services/api/RequestApi';
import { IUser } from '../../core/domain/user/User';
import { ViewHistory } from '../../core/domain/user/ViewHistory';
import { Music } from '../../core/domain/fm/Music';
import Bg from '../../components/Ui/Space/Bg/Bg';
import UserInfo from '../../components/User/SimpleInfo/SimpleInfo';
import UserViewCount from '../../components/User/ViewCount/ViewCount';
import RadioCtrl from '../../components/Radio/Ctrl/Ctrl';

const starStyle: CSSProperties = {
    position: 'absolute',
    top: 155,
    right: 65,
    backgroundColor: 'rgb(12,55,99)',
    zIndex: 100,
    width: 100,
    height: 100,
    borderRadius: '50%'
};

interface RadioState {
    musicList: Music[] | null;
    mySimpleInfo: IUser | null;
    viewHistory: ViewHistory | null;
}
export default class Radio extends Component<{}, RadioState> {
    public readonly state = {
        musicList: null,
        mySimpleInfo: null,
        viewHistory: null
    };
    public async componentDidMount(): Promise<void> {
        const limit = 0;
        const count = 2;
        // 并发请求
        // 如果使用Promis.all 其中一个请求出现异常了 其余接口也会失败
        // 这里使用 Primise.allSettled 规避这个问题
        const result = await Promise.allSettled([
            fetchMyMusics(),
            fetchMySimpleInfo(),
            fetchViewHistory(limit, count)
        ]);
        // 数组解构赋值语法
        const [musicList, mySimpleInfo, viewHistory] = result.map((res) => {
            if (res.status === 'fulfilled') {
                return res.value;
            }
            return null;
        }) as [Music[], IUser, ViewHistory]; //

        this.setState({ musicList, mySimpleInfo, viewHistory });
    }
    public render(): JSX.Element {
        return (
            <>
                <Bg
                    style={{
                        position: 'absolute',
                        left: 0,
                        right: 0,
                        top: 0,
                        bottom: 0,
                        zIndex: 0
                    }}
                />
                <div style={starStyle} />
                <div style={{ position: 'absolute', bottom: 35, left: 30, right: 30, zIndex: 100 }}>
                    <UserInfo userInfo={this.state.mySimpleInfo} />
                    <RadioCtrl />
                    <UserViewCount viewHistory={this.state.viewHistory} />
                </div>
            </>
        );
    }
}
